<script setup lang="ts">
import { isNullOrEmpty } from '@/utils/functions'
import Motion from "../utils/motion";
import { useRouter } from "vue-router";
import { message } from "@/utils/message";
import { loginRules } from "../utils/rule";
import { useNav } from "@/layout/hooks/useNav";
import type { FormInstance } from "element-plus";
import { useLayout } from "@/layout/hooks/useLayout";
import { useUserStoreHook } from "@/store/modules/user";
import { initRouter, getTopMenu } from "@/router/utils";
import { bg, avatar, illustration } from "../utils/static";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ref, reactive, toRaw, onMounted, onBeforeUnmount } from "vue";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";
// import Lock from "@iconify-icons/ri/lock-fill";
// import User from "@iconify-icons/ri/user-3-fill";
import { debounce, storageLocal } from "@pureadmin/utils";

import md5 from "blueimp-md5";
import { getSelfInfo, getCaptcha, getUserRole } from "@/api/user";
import { removeToken, setUserKey } from "@/utils/auth";
import { usePermissionStoreHook } from "@/store/modules/permission";
import { addPathMatch } from "@/router/utils";
import { resetHomePage, resetRouter } from "@/router/index";
import {
  usePageVariablesStoreHook,
  PLATFORM_Map,
  initOperateUnit,
  initManageUnit,
  initScreenUnit
} from "@/store/modules/pageVariables";
import { openProtocolContent, robotVerification } from '../utils/functions'
import { useGlobal } from "@pureadmin/utils";
import user from '@/assets/images/svg/user.svg'
import password from '@/assets/images/svg/password.svg'
import phone from '@/assets/images/svg/phone.svg'
import code from '@/assets/images/svg/code.svg'
import { getUserProjectRole } from "@/api/operate/work-management/work-management";
import { useDataDashboardThemeStoreHook } from '@/store/modules/data-dashboard-theme';

const config = ref(useGlobal().$config)
defineOptions({
  name: "Login"
});
const emits = defineEmits(["goRegist"]);
const router = useRouter();
const loading = ref(false);
const ruleFormRef = ref<FormInstance>();

const { initStorage } = useLayout();
initStorage();

const { dataTheme, dataThemeChange } = useDataThemeChange();
if (dataTheme.value) {
  dataThemeChange()
}

const { title } = useNav();
const codeImg = ref("");
const checked = ref(false);
// const ruleForm = reactive({
//   loginName: "admin",
//   password: "Admin123!",
//   captchaValue: "",
//   captchaId: null
// });
const ruleForm = reactive({
  loginName: "",// yclmxAdmin
  password: "",// yclmxAdmin123!
  captchaValue: "",
  captchaId: null
});
const operates = [
  {
    title: "手机号登录",
    currentPage: 1
  },
  {
    title: "账号注册",
    currentPage: 2
  }
];
const currentPage = computed(() => {
  return useUserStoreHook().currentPage;
});
const onLogin = async (formEl: FormInstance | undefined) => {
  storageLocal().removeItem("manage");
  storageLocal().removeItem("operate");
  if (!checked.value) {
    message(`请先勾选同意《${isNullOrEmpty(config.value.ProtocolName)}》`, { type: "warning" });
    return;
  };
  if (!formEl) return;
  await formEl.validate((valid) => {
    if (valid) {
      getRobotVerification()
    }
  });
};
const getRobotVerification = debounce(() => {
  let copy = JSON.parse(JSON.stringify(ruleForm));
  copy.password = md5(copy.password);
  robotVerification({
    fun: useUserStoreHook().loginByUsername,
    param: copy,
    successFun: () => {
      login()
    },
  })
}, 500, true)
const login = () => {
  // loading.value = true;
  // let copy = JSON.parse(JSON.stringify(ruleForm));
  // copy.password = md5(copy.password);
  // useUserStoreHook()
  //   .loginByUsername(copy)
  //   .then(res => {
  // 全部采取静态路由模式
  getSelfInfo().then(res => {
    let data = res.result;
    setUserKey(data.userInfo.nickname, data.permissions, data.userInfo);
    usePageVariablesStoreHook().clear();
    if (usePageVariablesStoreHook().getPlatform() == PLATFORM_Map.operate) {
      initOperateUnit().then(() => {
        getUserProjectRole().then(res1 => {
          if (data.userInfo.roles) {
            data.userInfo.roles.operate = res1.result.data
          } else {
            data.userInfo.roles = {
              operate: res1.result.data
            }
          }
          setUserKey(data.userInfo.nickname, res1.result.data, data.userInfo);
          resetHomePage()
          resetRouter();
          message("登录成功", { type: "success" });
        }).catch(() => {
          message('获取权限失败', { type: 'error' })
        })
      })
    } else if (usePageVariablesStoreHook().getPlatform() == PLATFORM_Map.manage) {
      initManageUnit().then(() => {
        getUserRole().then(res1 => {
          if (data.userInfo.roles) {
            data.userInfo.roles.manage = res1.result.data
          } else {
            data.userInfo.roles = {
              manage: res1.result.data
            }
          }
          setUserKey(data.userInfo.nickname, res1.result.data, data.userInfo);
          resetHomePage()
          resetRouter();
          message("登录成功", { type: "success" });
        }).catch(() => {
          message('获取权限失败', { type: 'error' })
        })
      });
    } else if (usePageVariablesStoreHook().getPlatform() == PLATFORM_Map.data || usePageVariablesStoreHook().getPlatform() == PLATFORM_Map.monitor) {
      initScreenUnit().then(() => {
        useDataDashboardThemeStoreHook().reDataDashboardThemeStore()
        resetHomePage()
        resetRouter();
        message("登录成功", { type: "success" });
      });
    } else {
      message("暂无可登录平台，请联系管理员！", { type: "error" });
      removeToken();
    }
  });
  // }).finally(() => {
  //   // getCodeImg();
  //   setTimeout(() => {
  //     loading.value = false;
  //   }, 1000);
  // });
}
const getCodeImg = () => {
  getCaptcha().then(res => {
    codeImg.value = res.result.captchaImg;
    ruleForm.captchaId = res.result.captchaId;
  });
};

onMounted(() => {
  // getCodeImg();
});
</script>

<template>
  <div>
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="loginRules" size="large">
      <Motion :delay="100">
        <el-form-item :rules="[
          {
            required: true,
            message: '请输入账号',
            trigger: 'blur'
          }
        ]" prop="loginName">
          <el-input v-model="ruleForm.loginName" clearable placeholder="账号" v-bind="$attrs"
            :prefix-icon="useRenderIcon(user)" />
        </el-form-item>
      </Motion>

      <Motion :delay="150">
        <el-form-item prop="password">
          <el-input v-model="ruleForm.password" clearable show-password placeholder="密码" v-bind="$attrs"
            :prefix-icon="useRenderIcon(password)" />
        </el-form-item>
      </Motion>

      <!-- <Motion :delay="200">
                <el-form-item prop="captchaValue">
                    <el-input v-model="ruleForm.captchaValue" :placeholder="'请输入验证码'" v-bind="$attrs"
                        @keyup.enter="onLogin(ruleFormRef)" :prefix-icon="useRenderIcon(code)">
                        <template v-slot:append>
                            <el-image style="height: var(--el-input-height)" :src="codeImg"
                                @click="getCodeImg"></el-image>
                        </template>
</el-input>
</el-form-item>
</Motion> -->
      <Motion :delay="200">
        <el-button class="w-full mt-4" size="default" type="primary" :loading="loading" @click="onLogin(ruleFormRef)">
          登录
        </el-button>
      </Motion>
      <Motion :delay="300">
        <!-- <el-form-item> -->
        <div class="w-full flex-bc">
          <div class="flex-c">
            <el-checkbox v-model="checked">
              <div class="text-[#fff]">我已阅读并同意</div>
            </el-checkbox>
            <el-button link type="primary" style="--el-color-primary: #fe861c;--el-color-primary-light-5: #fe861c;"
              @click="openProtocolContent(config.ProtocolName, config.ProtocolContent)">
              《{{ isNullOrEmpty(config.ProtocolName) }}》
            </el-button>
          </div>
          <div class="flex-c" style="--el-color-primary: #fff;--el-color-primary-light-5: #fff;">
            <el-button link type="primary" @click="emits('goRegist')">
              立即注册
            </el-button>
          </div>
        </div>
        <!-- </el-form-item> -->
      </Motion>

    </el-form>
  </div>
</template>

<style scoped>
@import url("@/style/login.css");
</style>

<style lang="scss" scoped>
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}
</style>
